#include "optiondialog.h"
#include "ui_option.h"
#include <QtDebug>
#include <QRegExp>
#include <QValidator>

optionDialog::optionDialog()
        :option(new Ui::Option),port(8888),isClient(true)
{
    //完成ui的初始化工作
    option->setupUi(this);
    ip = new  QHostAddress(QHostAddress::LocalHost);
    //连接确定信号到getOption函数
    option->serverGroupBox->hide();
    option->line_ip->setInputMask(tr("000.000.000.000"));
    QRegExp rx("[0-9]\\d*");
    QValidator *validator = new QRegExpValidator(rx,0);
    option->line_port->setValidator(validator);
    //option->line_port->setMaxLength(65536);
    option->line_ip->setText(ip->toString());
    option->line_port->setText("8888");
    option->line_port_server->setText("8888");
    //option->clientGroupBox->hide();
    connect(option->buttonBox,SIGNAL(accepted()),this,SLOT(getOption()));
    connect(option->buttonBox,SIGNAL(rejected()),this,SLOT(cleanOption())); //取消就关闭
    connect(option->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(changeShow(int)));
}
optionDialog::~optionDialog()
{
   // free(ip);
}

//获取ip,port信息
void optionDialog::getOption()
{
   // qDebug() << "coming in";
    bool ok;
    qDebug()<<isClient;
    if(isClient)
    {
        if(ip->setAddress(option->line_ip->text()))
        {
         //如果设置IP成功
             port = option->line_port->text().toInt(&ok,10);

        }
    }
    else
    {
        ip->setAddress(QHostAddress::LocalHost);
        port = option->line_port_server->text().toInt(&ok,10);
    }

     qDebug()<<ip->toString();
     emit optionChanged(isClient,ip,port);
    this->close();
}

void optionDialog::cleanOption()
{
    option->line_ip->clear();
    option->line_port->clear();
}

void optionDialog::changeShow(int index)
{
    if(index == 0)
    {
        option->serverGroupBox->setVisible(false);
        option->clientGroupBox->setVisible(true);
        isClient = true;
    }
    else
    {
        option->serverGroupBox->setVisible(true);
        option->clientGroupBox->setVisible(false);
        isClient = false;
    }
}
